import { IPSDEFormTabPanel } from '@ibiz/dynamic-model-api';
import { FormDetailController } from './form-detail-controller';

/**
 * 分页部件模型
 *
 * @export
 * @class FormTabPanelController
 * @extends {FormDetailController}
 */
export class FormTabPanelController extends FormDetailController {
  /**
   * @description 表单分页部件项模型实例对象
   * @type {IPSDEFormTabPanel}
   * @memberof FormTabPanelController
   */
  public model!: IPSDEFormTabPanel;

  /**
   * 被激活分页
   *
   * @type {string}
   * @memberof FormTabPanelController
   */
  public activatedPage: string = '';

  /**
   * 选中激活状态
   *
   * @type {string}
   * @memberof FormTabPanelController
   */
  public clickActiviePage: string = '';

  /**
   * 分页子成员
   *
   * @type {any[]}
   * @memberof FormTabPanelController
   */
  public tabPages: any[] = [];

  /**
   * Creates an instance of FormTabPanelController.
   * FormTabPanelController 实例
   *
   * @param {*} [opts={}]
   * @memberof FormTabPanelController
   */
  constructor(opts: any = {}) {
    super(opts);
    this.tabPages = [...opts.tabPages];
    if (this.tabPages.length > 0) {
      this.activatedPage = this.tabPages[0].name;
    }
  }

  /**
   * 设置激活分页
   *
   * @memberof FormTabPanelController
   */
  public setActiviePage(): void {
    if (!this.parentController) {
      return;
    }
    const detailsModel: any = this.parentController.detailsModel;
    const index = this.tabPages.findIndex(
      (tabpage: any) =>
        Object.is(tabpage.name, this.clickActiviePage) &&
        Object.is(tabpage.name, this.activatedPage) &&
        detailsModel[tabpage.name].visible,
    );
    if (index !== -1) {
      return;
    }

    this.tabPages.some((tabpage: any) => {
      if (detailsModel[tabpage.name].visible) {
        this.activatedPage = tabpage.name;
        return true;
      }
      return false;
    });
  }

  /**
   * 选中页面
   *
   * @param {*} $event
   * @returns {void}
   * @memberof FormTabPanelController
   */
  public clickPage($event: any): void {
    if (!$event) {
      return;
    }

    this.clickActiviePage = $event;
    this.activatedPage = $event;
  }
}
